package com.izhar.answeringmachine.service.Impl;

import com.izhar.answeringmachine.Entity.SubmitResult;
import com.izhar.answeringmachine.service.ICompile;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.charset.Charset;

/**
 * @author izhar
 */
@Service
@Slf4j
public class CompileImpl implements ICompile {

    /**
     * base目录  用户方面更换windows和linux系统下的用户代码存放路径
     */
    @Value("${question.filePath}")
    private String baseLocation;

    @SneakyThrows
    @Override
    public void compile(String userId, String questionId, SubmitResult submitResult) {

        //刚开始200，后续出现错误，会更正
        submitResult.setResultCode("200");

       String filePath = baseLocation+userId+"_"+questionId+"/Question.java";
       StringBuilder errMsg = new StringBuilder();

        String[] location = {"javac","-encoding","utf-8",filePath};
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(location);
        } catch (IOException e) {
            log.error("IO exception");
            throw new RuntimeException("IO exception");
        }

        //输入输出流，错误输入流
        InputStream input = process.getInputStream();
        OutputStream out = process.getOutputStream();
        InputStream err = process.getErrorStream();

        BufferedReader errReader = null;
        errReader = new BufferedReader(new InputStreamReader(err,"gbk"));

        String readLine = "";

        //错误信息放到errMsg里，
        while((readLine = errReader.readLine()) != null){
            errMsg.append(readLine).append("\\n");
        }


        if (!"".equals(errMsg.toString().trim())){
            log.error("compile error:"+errMsg);

            //切割字符串，把前面的Java文件路径切掉
            String[] split = errMsg.toString().split("Question.java:");

            //错误信息写入运行结果打包类
            submitResult.setResultCode("4");
            submitResult.setErrorDetail(split[1]);
            errMsg.setLength(0);
            //throw new RuntimeException("compile error:"+errMsg);
        }
    }
}
